package com.labs.laba_01;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;

import com.labs.laba_01.StudentGroup.StudRec;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnDismissListener;
import android.text.Editable;
import android.util.Log;
import android.view.*;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;


public class MainActivity extends Activity {

	final static byte DIALOG_ADD_GROUP = 1;
	final static byte DIALOG_ADD_STUDENT = 2;
	final static String LOG_TAG = "elisp";

	private ArrayList<HashMap<String,String>> mList = new ArrayList<HashMap<String,String>>();
	private SimpleAdapter adapter;
	private ListView mListView;

	private ArrayList<StudentGroup> groupList;
	private StudentGroup currentGroup;
	private Dialog dialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        //mSettings = getSharedPreferences("groupList", MODE_PRIVATE);
        groupList = new ArrayList<StudentGroup>();
        currentGroup = null;
    }

    @Override
    protected void onResume() {
    	super.onResume();
    	setContentView(R.layout.groups_list);
    	//
    	mListView = (ListView)findViewById(R.id.listView1);
    	mListView.setOnItemClickListener(new OnItemClickListener() {
    		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    			Log.d(LOG_TAG, "itemClick: position = " + position + ", id = "+ id);
    			if(currentGroup==null)openGroupContent(position);
		    }
		});
    	if(currentGroup==null) refreshViewList();
    	else refreshViewListForGroup();
    }

    @Override 
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode==KeyEvent.KEYCODE_BACK) && currentGroup!=null) {
        	currentGroup = null;
        	refreshViewList();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	menu.add(0,1,0,"add group");
    	menu.add(0,2,0,"exit");
    	menu.add(1,3,0,"add student");
    	menu.add(1,4,0,"back");
    	menu.add(1,5,0,"sort by num");
    	menu.add(1,6,0,"sort by app");
        return super.onCreateOptionsMenu(menu);
    }
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
    	if(currentGroup==null){
    		menu.setGroupVisible(0, true);
    		menu.setGroupVisible(1, false);
    	}else{
    		menu.setGroupVisible(0, false);
    		menu.setGroupVisible(1, true);
    	}
    	Log.d(LOG_TAG, "on Prepare to option menu");
    	return super.onPrepareOptionsMenu(menu);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	if(item.getTitle().equals("add group")){
    		showDialog(DIALOG_ADD_GROUP);
    	}else if(item.getTitle().equals("exit")){
    		finish();
    	}else if(item.getTitle().equals("add student")){
    		showDialog(DIALOG_ADD_STUDENT);
    	}else if(item.getTitle().equals("back")){
    		currentGroup = null;
    		refreshViewList();
    	}else if(item.getTitle().equals("sort by num")){
    		sortByNumber();
    	}else if(item.getTitle().equals("sort by app")){
    		sortByAppraisal();
    	}
    	return super.onOptionsItemSelected(item);
    }

    public void sortByNumber(){
    	currentGroup.sortByNumber();
    	refreshViewListForGroup();
    }
    public void sortByAppraisal(){
    	currentGroup.sortByAppraisal();
    	refreshViewListForGroup();
    }

    private void openGroupContent(int pos){
    	currentGroup = groupList.get(pos);
    	refreshViewListForGroup();
//    	Intent newIntent = new Intent(getBaseContext(), StudentListActivity.class);
//    	newIntent.p ("Group", sg);
//        startActivity(newIntent);
    }
    public void addGroup(CharSequence c){
    	StudentGroup sg = new StudentGroup(c);
    	groupList.add(sg);
    	Toast.makeText(getApplicationContext(), c+" added", Toast.LENGTH_SHORT).show();
    	refreshViewList();
    }
    public void addStudent(CharSequence n, CharSequence s, int a){
    	Student st = Student.getNewStudent(n, s);
    	if(currentGroup.addStudent(st, a)) Toast.makeText(getApplicationContext(), n+" added", Toast.LENGTH_SHORT).show();
    	else Toast.makeText(getApplicationContext(), n+" didn't added", Toast.LENGTH_SHORT).show();
    	refreshViewListForGroup();
    }

    public void refreshViewList(){
    	setTitle("Group list");
    	mList.clear();
    	if(!groupList.isEmpty()){
    		HashMap<String,String> m;
	    	for(StudentGroup stg: groupList){
	    		m = new HashMap<String,String>();
	    		m.put("l1",stg.getCaption().toString());
	    		m.put("l2",BigInteger.valueOf(stg.getCount()).toString());
	    		mList.add(m);
	    	}
	    }
    	adapter = new SimpleAdapter(this, mList, android.R.layout.simple_list_item_2, new String[]{"l1","l2"}, new int[]{android.R.id.text1, android.R.id.text2});
		mListView.setAdapter(adapter);
    }
    public void refreshViewListForGroup(){
    	ArrayList<StudRec> strList = currentGroup.getList();
    	setTitle(currentGroup.getCaption());
    	mList.clear();
    	if(!strList.isEmpty()){
    		//ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>(); // 4 field
    		HashMap<String, String> m;
	    	for(StudRec str: strList){
	    		m = new HashMap<String,String>();
	    		m.put("num",BigDecimal.valueOf(str.getNumber()).toString());
	    		m.put("n",str.getStudent().getName().toString());
	    		m.put("s",str.getStudent().getSurname().toString());
	    		m.put("a",BigDecimal.valueOf(str.getAppraisal()).toString());
	    		mList.add(m);
	    	}
	    }
    	adapter = new SimpleAdapter(this, mList, R.layout.student_list_item, new String[]{"num","n","s","a"}, new int[]{R.id.TextView0, R.id.TextView1, R.id.textView2, R.id.textView3});
		mListView.setAdapter(adapter);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
    	Log.d(LOG_TAG, "Create dialog with id="+id);
    	if(DIALOG_ADD_GROUP==id){
    		LinearLayout custView = (LinearLayout) getLayoutInflater().inflate(R.layout.add_group, null);
	        final EditText tEdit = (EditText) custView.findViewById(R.id.editText1);
	        tEdit.setText("");
	        AlertDialog.Builder adb = new AlertDialog.Builder(this);
	        adb.setTitle("creat new group");
	        adb.setPositiveButton("OK", new OnClickListener(){
	        	@Override
				public void onClick(DialogInterface dialog, int which) {
	        		Editable q = tEdit.getText();
					if(q.toString().trim().length()>0){
						addGroup(q.toString().trim());
					}else{
						Toast.makeText(getApplicationContext(), "empty value", Toast.LENGTH_SHORT).show();
					}
					dialog.dismiss();
					tEdit.setText("");
				}
	        });
	        adb.setNegativeButton("Cancel", null);
	        adb.setView(custView);
	        tEdit.requestFocus();
	        dialog = adb.create();
	        dialog.getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);
	        dialog.setOnCancelListener(new OnCancelListener() {
	        	public void onCancel(DialogInterface dialog) {
	        		Log.d(LOG_TAG, "Cancel");
	        	}
	        });
	        dialog.setOnDismissListener(new OnDismissListener() {
	        	public void onDismiss(DialogInterface dialog) {
	        		Log.d(LOG_TAG, "Dismiss");
	        	}
	        });
	        return dialog;
      }else if(DIALOG_ADD_STUDENT==id){
    	  LinearLayout custView = (LinearLayout) getLayoutInflater().inflate(R.layout.add_student, null);
    	  final EditText tEdApp = (EditText) custView.findViewById(R.id.editText3);
    	  final EditText tEdSurname = (EditText) custView.findViewById(R.id.editText2);
    	  final EditText tEdName = (EditText) custView.findViewById(R.id.editText1);
    	  tEdApp.setText("");
    	  tEdSurname.setText("");
    	  tEdName.setText("");
    	  AlertDialog.Builder adb = new AlertDialog.Builder(this);
    	  adb.setTitle("creat new student");
    	  adb.setPositiveButton("OK", new OnClickListener(){
    		  @Override
    		  public void onClick(DialogInterface dialog, int which) {
    			  Editable qn = tEdName.getText();
    			  Editable qs = tEdSurname.getText();
    			  Editable qa = tEdApp.getText();
    			  if(qn.toString().trim().length()>0 && qs.toString().trim().length()>0){
    				  int qav = 0;
    				  if(qa.toString().trim().length()>0) qav = Integer.parseInt(qa.toString());
    				  addStudent(qn.toString().trim(), qs.toString().trim(), qav);
    			  }else{
    				  Toast.makeText(getApplicationContext(), "empty one of values", Toast.LENGTH_SHORT).show();
    			  }
    			  dialog.dismiss();
    			  tEdApp.setText("");
    			  tEdSurname.setText("");
		    	  tEdName.setText("");
		    	  tEdName.requestFocus();
    		  }
    	  });
    	  adb.setNegativeButton("Cancel", null);
	      adb.setView(custView);
	      tEdName.requestFocus();
	      dialog = adb.create();
	      dialog.getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);
	      dialog.setOnCancelListener(new OnCancelListener() {
	    	  public void onCancel(DialogInterface dialog) {
	    		  Log.d(LOG_TAG, "Cancel");
	          }
	      });
	      dialog.setOnDismissListener(new OnDismissListener() {
	    	  public void onDismiss(DialogInterface dialog) {
	    		  Log.d(LOG_TAG, "Dismiss");
	    	  }
	      });
	      return dialog;
      }
      return super.onCreateDialog(id);
    }
}
